package com.mxf.code.chain_params;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @author 28382
 */
@Service
public class DataValidHandlerChain {

    // 自动注入
    @Autowired
    private List<DataValidHandler> handlers;

    /**
     * 创建数据验证责任链
     */
    @PostConstruct
    public void init() {
        handlers.sort(Comparator.comparingInt(h -> getOrder(h.getClass())));
        for (int i = 0; i < handlers.size() - 1; i++) {
            handlers.get(i).setNext(handlers.get(i + 1));
        }
    }

    private int getOrder(Class<?> clazz) {
        Order order = clazz.getDeclaredAnnotation(Order.class);
        return (order != null) ? order.value() : Ordered.LOWEST_PRECEDENCE;
    }

    /**
     * 开始处理数据
     */
    public Result<Void> handle(Map<String, ParamRequest> data) {
        return handlers.get(0).handle(data);
    }

}
